Ext.namespace("Sol.widgets");
Sol.widgets.MainMenu = function(appsMenu, config) {
	Sol.widgets.MainMenu.superclass.constructor.call(this, config); 
    this.setRootNode(new Ext.tree.TreeNode({text: 'Menú', id: 'menu', singleClickExpand: true, expanded:true }));
    this.createItems(appsMenu, this.getRootNode(), 1);
};
Ext.extend(Sol.widgets.MainMenu, Ext.tree.TreePanel, {
  	loadState: function() {
		var expandedmenuitems = Ext.state.Manager.get('expandedmenuitems'), node;
		if (!Ext.isEmpty(expandedmenuitems)) {
			var menus = expandedmenuitems.split(",");
			for(var i in menus) {
				node = this.getNodeById(menus[i]);
				if (node && !Ext.isEmpty(node))
					node.expand(false, false);
			}
		}
		this.body.dom.scrollTop = Ext.state.Manager.get('menuscrolltop');		
		this.body.dom.scrollLeft = Ext.state.Manager.get('menuscrollleft');
  	},
	saveExpandedItems: function(node) {
		if (node.isExpanded()) {
			if (node.parentNode && !node.parentNode.isExpanded()) 
				return;
			var expandedmenuitems = Ext.state.Manager.get('expandedmenuitems'), value;
			if (Ext.isEmpty(expandedmenuitems)) value = node.id
			else value = expandedmenuitems + ',' + node.id;
			Ext.state.Manager.set('expandedmenuitems', value);
		}
	},
	saveState2: function() {
		Ext.state.Manager.set('expandedmenuitems', null);
		Ext.state.Manager.set('menuscrolltop', this.body.dom.scrollTop);
		Ext.state.Manager.set('menuscrollleft', this.body.dom.scrollLeft);
		this.getRootNode().cascade(this.saveExpandedItems);
	},
  	createItems: function(appsMenu, menunode, level) {
		var menuitem;
		for (var i = 0; i < appsMenu.length; i += 1) {
			if (appsMenu[i]['menu']){
				menuitem = new Ext.tree.TreeNode({text:appsMenu[i]['nombre'], singleClickExpand:true, id: menunode.id + level + i});
				menunode.appendChild(menuitem);
				this.createItems(appsMenu[i]['menu'], menuitem, level + 1);				
			} else {
				menuitem = new Ext.tree.TreeNode({text:appsMenu[i]['nombre'], href:CONTEXT_PATH+appsMenu[i]['url'], id: menunode.id + i});
				menunode.appendChild(menuitem);
			}
		}
  	}
});


